package com.daohang361.imqq.XmlLoader;

import java.io.File;   
import java.io.IOException;   
import javax.xml.parsers.DocumentBuilder;   
import javax.xml.parsers.DocumentBuilderFactory;   
import javax.xml.parsers.ParserConfigurationException;   
import org.w3c.dom.Attr;   
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;   
import org.w3c.dom.Element;   
import org.w3c.dom.NamedNodeMap;   
import org.w3c.dom.Node;   
import org.w3c.dom.NodeList;   
import org.xml.sax.SAXException;   
import com.daohang361.imqq.encoder.InterfaceEncoder;
import com.daohang361.imqq.exception.UnKnownCommand;
import com.daohang361.imqq.protocol.Myproper;
import com.daohang361.imqq.ServerContex.ServerContex;
/** 
 * @author naner E-mail:likun3344@163.com 
 * @create time：2011-4-14 下午04:50:54 
 * 校验xml以及解析xml
 */ 
public class InitDomParser {   
  
    @SuppressWarnings("unused")
	public static void init() throws ParserConfigurationException,   
            SAXException, IOException {   
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();   
        DocumentBuilder builder = factory.newDocumentBuilder();   
        String fileName = "conf/defualtInit.xml";   
        File file = null;   
            file = new File(fileName);   
            if (!file.exists()) {   
                System.out.println("xml文件不存在！");   
                fileName = "";   
        }   
        boolean validate = new InitXMLValidateDTD().XMLValidateDTD(file);   
        if (validate) {   
            System.out.println("通过DTD校验！");   
            Document doc = builder.parse(file);   
			Element root = doc.getDocumentElement();   
//            printElement(root);   
            initDufaltXmlLoader(fileName);
        } else {   
            System.out.println("该XML文件未通过DTD校验解析终止！！！");   
        }   
    }   
  
    /**
     * 获取默认初始化xml规则
     * @param fileName
     */
    public static void initDufaltXmlLoader(String fileName)
    {
    	long lasting =System.currentTimeMillis(); 
    		try {
				File f=new File(fileName); 
				DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); 
				DocumentBuilder builder=factory.newDocumentBuilder(); 
				Document doc = builder.parse(f); 
				NodeList nl = doc.getElementsByTagName("encoder"); 
				for (int i=0;i<nl.getLength();i++)
					{ 
					String command= doc.getElementsByTagName("command").item(i).getFirstChild().getNodeValue(); 
					int sendtimes =Integer.parseInt(doc.getElementsByTagName("sendtimes").item(i).getFirstChild().getNodeValue()); 
					String temp= doc.getElementsByTagName("ignore").item(0).getAttributes().getNamedItem("value").getTextContent(); 
					boolean ignore =false;
					if(temp.equals("true"))
						ignore=true;
					InterfaceEncoder encoder=Myproper.getEncoder(Integer.parseInt(command,16));
					if(encoder==null)
						throw new UnKnownCommand("未知命令'"+command+"'将被忽略");
					encoder.setIgnore(ignore);
					for(int j=0;j<sendtimes;j++){
						ServerContex.saveEncoder(encoder);
						ServerContex.saveCommand(Integer.parseInt(command,16));
					}
					System.out.print(" command:"+command);
					System.out.print(" sendtimes:"+sendtimes);
					System.out.print(" ignore:"+ignore);
					System.out.print("\n");
					}
			} catch (NumberFormatException e) {
				System.out.println("请检查sendtimes是否为整数.");
				e.printStackTrace();
			} catch (DOMException e) {
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (IOException e) {
				System.out.println("请检查xml文件路径.");
				e.printStackTrace();
			} catch(Exception e){
				e.printStackTrace();
			}
    	
    	System.out.println("运行时间："+(System.currentTimeMillis() - lasting)+" 毫秒"); 
		System.out.println("总共初始化步骤为 :"+ServerContex.getSize());
    }
    /**
     * 通用的打印节点
     * @param e
     */
    public static void printElement(Element e) { 
        System.out.print("<" + e.getTagName());   
        NamedNodeMap map = e.getAttributes();   
        for (int i = 0; i < map.getLength(); i++) {   
            Attr attr = (Attr) map.item(i);   
            System.out.print(" " + attr.getName() + "=\"" + attr.getValue()   
                    + "\"");   
        }   
        System.out.print(">");   
        NodeList list = e.getChildNodes();   
        for (int i = 0; i < list.getLength(); i++) {   
            Node n = list.item(i);   
            if (n.getNodeType() == Node.ELEMENT_NODE) {   
                Element en = (Element) n;   
                printElement(en);   
            } else {   
                System.out.println(""+n.getTextContent());   
            }   
  
        }   
        System.out.print("</" + e.getTagName() + ">");   
    }   
  
}  
